// 井字棋游戏逻辑
let board;
let currentPlayer;
let gameActive;

// 获胜组合
const winningCombinations = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8], // 行
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8], // 列
    [0, 4, 8],
    [2, 4, 6]  // 对角线
];

// DOM元素
const statusElement = document.getElementById('status');
const boardElement = document.getElementById('board');
const resetButton = document.getElementById('reset-button');

// 初始化游戏
function init() {
    board = Array.from({ length: 9 }, () => '');
    currentPlayer = 'X';
    gameActive = true;
    
    statusElement.textContent = `玩家${currentPlayer}的回合`;
    renderBoard();
}

// 渲染棋盘
document.addEventListener('DOMContentLoaded', function() {
    boardElement.innerHTML = '';
    for (let i = 0; i < 9; i++) {
        const cell = document.createElement('div');
        cell.className = 'cell';
        cell.dataset.index = i;
        cell.addEventListener('click', handleCellClick);
        boardElement.appendChild(cell);
    }
});

// 处理单元格点击
function handleCellClick(e) {
    const cell = e.target;
    const index = parseInt(cell.dataset.index);

    if (!gameActive || board[index] !== '') {
        return;
    }

    board[index] = currentPlayer;
    cell.textContent = currentPlayer;

    if (checkWinner(currentPlayer)) {
        statusElement.textContent = `玩家${currentPlayer}获胜！`;
        gameActive = false;
        return;
    }

    if (board.every(cell => cell !== '')) {
        statusElement.textContent = "平局！";
        gameActive = false;
        return;
    }

    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
    statusElement.textContent = `玩家${currentPlayer}的回合`;
}

// 检查胜利者
function checkWinner(player) {
    return winningCombinations.some(combination => {
        return combination.every(index => board[index] === player);
    });
}

// 重置游戏
resetButton.addEventListener('click', () => {
    // 重新初始化游戏状态
    init();
    
    // 清空棋盘显示并移除点击事件
    const cells = document.querySelectorAll('.cell');
    cells.forEach(cell => {
        cell.textContent = '';
        // 移除可能存在的胜利高亮样式
        cell.classList.remove('winning-cell');
        // 移除点击事件监听器
        cell.removeEventListener('click', handleCellClick);
        // 重新添加点击事件监听器
        cell.addEventListener('click', handleCellClick);
    });
    
    // 确保棋盘完全清空
    board = Array.from({ length: 9 }, () => '');
});

// 开始游戏
init();